import {Loading,Message} from 'element-ui';
import auto from 'async/auto';
import router from '@/router';
import * as types from '@/store/types';

const INDEX_PREFIX = 'result';

/**
 * http請求統一出口，異常統一提示處理，支持三種請求形式，內置請求loading控制，(注意方式2不支持隊列，隊列功能請使用方式3)
 * 1.單接口請求
 * httpClient(api, data, function(error, result) {});
 * 2.多接口請求,參數與api一一對應，results返回結果一一對應api請求結果result1,result2,result3
 * httpClient([api1,api2,api3], [data1,data2,data3], function(error, results) {});
 * 3.通用模式httpClient({
      api2(callback) {
        api2().then(_=>{
          callback(null,_)
        },error=>{
          callback(error)
        });
      },
      api3: ['login2', function(results, callback) {
        api3().then(_=>{
          callback(null,_)
        },error=>{
          callback(error)
        });
      }]
     }
    },function(error, result) {});
 * @param config 請求配置
 * @param data 參數 可選
 * @param callback 回調函數 必傳
 * @param closeloading 是否關閉loading效果 默認false
 */
export default (config, ...autoParams) => {

  if(autoParams.length===0){
    throw '回調函數不能爲空';
  }

  let asyncs = config;
  let params = null;
  let callback = null;
  let closeloading = false;

  autoParams.forEach((item,i)=>{
    if(_.isFunction(item)){
      callback = item;
    }else if(_.isObject(item)||_.isString(item)||_.isNumber(item)){
      params = item;
    }else if(_.isBoolean(item)){
      if(i===0){
        params = item;
      }else{
        closeloading = item;
      }
    }else{
      throw '參數傳入錯誤';
    }
  });

  let isFunction = false;
  if (_.isFunction(asyncs)) {
    asyncs = [asyncs];
    params = [params];
    isFunction = true;
  }

  //自動構建回調函數
  if (_.isArray(asyncs)) {
    const list = asyncs.map((item, i) => {
      return (callback) => {
        item(params[i]).then(result => {
          callback(null, result);
        }, error => {
          callback(error);
        });
      };
    });

    const obj = {};
    list.forEach((item, i) => {
      obj[INDEX_PREFIX + i] = item;
    });
    asyncs = obj;
  }

  let loadingInstance =null;
  if(!closeloading){
    loadingInstance = Loading.service();
  }

  auto(asyncs, function(err, results) {
    if(!closeloading) {
      loadingInstance.close();
    }

    if(err){

      if(err.state){
        if (err.state.code === types.RES_UNLOGIN_ERROR_CODE) {
          router.push({name: 'login'});
          return;
        }else if(err.state.code===types.RES_BASE_ERROR_CODE){
          Message.error(err.state.message+' '+err.body.errorMsg);
        }
      }else{

      }

    }

    callback(err, isFunction ? results[INDEX_PREFIX + 0] : results);
  });

}

